package cn.zerlynn.sql.dialect.factory;

import cn.zerlynn.sql.dialect.api.IDialect;
import cn.zerlynn.sql.dialect.exception.DialectNotFoundException;
import cn.zerlynn.sql.dialect.impl.MySQLDialect;

import java.sql.Connection;
import java.sql.SQLException;
/**
 * DialectFactory: Factory for creating dialect instances using an enum.
 *
 * @author: zerlynn
 * @createTime: 2024/10/24 0:08
 */
public enum DialectFactory {

    MYSQL("mysql", new MySQLDialect());
//    POSTGRESQL("postgresql", new PostgreSQLDialect()),
//    ORACLE("oracle", new OracleDialect()),
//    SQLSERVER("sqlserver", new SQLServerDialect()),
//    DM("dm", new DmDialect()),
//    SQLITE("sqlite", new SQLiteDialect());

    private final String productName;
    private final IDialect dialect;

    DialectFactory(String productName, IDialect dialect) {
        this.productName = productName;
        this.dialect = dialect;
    }

    /**
     * 根据数据库产品名获取对应的方言实例。
     *
     * @param productName 数据库产品名称
     * @return 对应的 IDatabaseDialect 实例
     */
    public static IDialect getDialect(String productName) {
        for (DialectFactory factory : values()) {
            if (factory.productName.equals(productName.toLowerCase())) {
                return factory.dialect;
            }
        }
        throw new DialectNotFoundException("未找到对应的方言实现: " + productName);
    }

    /**
     * 从数据库连接中自动检测并返回方言实例。
     *
     * @param connection 数据库连接
     * @return 对应的 IDatabaseDialect 实例
     */
    public static IDialect getDialect(Connection connection) {
        try {
            String productName = connection.getMetaData().getDatabaseProductName();
            return getDialect(productName);
        } catch (SQLException e) {
            throw new DialectNotFoundException("无法获取数据库产品名称", e);
        }
    }
}
